<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { TSubject } from '@/Types/subject'
import {
	addSubjectService,
	deleteSubjectService,
	getSubjectListService
} from '@/api/education/subject'

/**
 * 模块名: 科目管理
 * 代码描述: 支持批量添加和删除科目
 * 创建时间: 2024/07/23
 */

// 科目列表
const subjectList = ref<TSubject[]>([])
// 多选选中的科目
const multipleSelection = ref<TSubject[]>([])
// 加载状态
const loading = ref(false)
// 对话框显示状态
const dialogVisible = ref(false)
// 批量添加科目
const newSubjects = ref('')
// 表单校验规则
const rules = reactive({
	newSubjects: [{ required: true, message: '请输入要添加的科目', trigger: 'blur' }]
})
// 表单引用
const formRef = ref()

// 获取科目列表
const getSubjectList = async () => {
	loading.value = true
	try {
		const res = await getSubjectListService()
		if (res.data.code === 1) {
			subjectList.value = res.data.data
		} else {
			ElMessage.error(res.data.mes)
		}
	} catch (error) {
		console.error('获取科目列表失败', error)
		ElMessage.error('获取科目列表失败')
	} finally {
		loading.value = false
	}
}

// 表格多选处理
const handleSelectionChange = (selection: TSubject[]) => {
	multipleSelection.value = selection
}

// 删除单个科目
const handleDelete = (row: TSubject) => {
	ElMessageBox.confirm('确认删除该科目?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			const res = await deleteSubjectService(row.id )
			if (res.data.code === 1) {
				subjectList.value = subjectList.value.filter((item) => item.id !== row.id)
				ElMessage.success('删除成功')
			} else {
				ElMessage.error(res.data.mes)
			}
		})
		.catch(() => {
			// 取消删除
		})
}

// 批量删除科目
const handleBatchDelete = () => {
	if (multipleSelection.value.length === 0) {
		ElMessage.warning('请至少选择一个科目')
		return
	}

	ElMessageBox.confirm(`确认删除选中的 ${multipleSelection.value.length} 个科目?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
		.then(async () => {
			// 获取所选科目的ID
			const ids = multipleSelection.value.map((item) => item.id)

			try {
				// 逐个删除所选科目
				for (const id of ids) {
					const res = await deleteSubjectService(id )
					if (res.data.code !== 1) {
						ElMessage.error(`删除ID为${id}的科目失败: ${res.data.mes}`)
						// 刷新列表
						getSubjectList()
						return
					}
				}

				// 全部删除成功后，更新前端列表
				subjectList.value = subjectList.value.filter((item) => !ids.includes(item.id))
				multipleSelection.value = []
				ElMessage.success('批量删除成功')
			} catch (error) {
				console.error('批量删除科目失败', error)
				ElMessage.error('批量删除科目失败')
				// 刷新列表
				getSubjectList()
			}
		})
		.catch(() => {
			// 取消删除
		})
}

// 打开添加科目对话框
const openAddDialog = () => {
	dialogVisible.value = true
	newSubjects.value = ''
}

// 批量添加科目
const handleBatchAdd = async () => {
	if (!newSubjects.value.trim()) {
		ElMessage.warning('请输入要添加的科目')
		return
	}

	// 将输入的科目按行分割成数组
	const subjects = newSubjects.value
		.split('\n')
		.map((item) => item.trim())
		.filter((item) => item)

	if (subjects.length === 0) {
		ElMessage.warning('没有有效的科目')
		return
	}

	try {
		// 逐个添加科目
		let successCount = 0
		for (const subject of subjects) {
			// 按API要求构造参数
			const params = { subject }
			const res = await addSubjectService(params)
			if (res.data.code === 1) {
				successCount++
			} else {
				ElMessage.error(`添加科目 "${subject}" 失败: ${res.data.mes}`)
			}
		}

		if (successCount > 0) {
			ElMessage.success(`成功添加 ${successCount} 个科目`)
			dialogVisible.value = false
			// 刷新科目列表
			getSubjectList()
		}
	} catch (error) {
		console.error('批量添加科目失败', error)
		ElMessage.error('批量添加科目失败')
	}
}

// 页面加载时获取科目列表
onMounted(() => {
	getSubjectList()
})
</script>

<template>
	<div class="subject-manage">
		<div class="subject-header">
			<h2>科目管理</h2>
			<div class="operation-buttons">
				<el-button type="primary" @click="openAddDialog">
					<el-icon><Plus /></el-icon>批量添加
				</el-button>
				<el-button
					type="danger"
					@click="handleBatchDelete"
					:disabled="multipleSelection.length === 0"
				>
					<el-icon><Delete /></el-icon>批量删除
				</el-button>
			</div>
		</div>

		<el-card shadow="hover" class="subject-table-card">
			<el-table
				v-loading="loading"
				:data="subjectList"
				style="width: 100%"
				border
				@selection-change="handleSelectionChange"
			>
				<el-table-column type="selection" width="55" />
				<el-table-column label="序号" type="index" width="80" />
				<el-table-column prop="id" label="科目ID" width="120" />
				<el-table-column prop="subject" label="科目名称" />
				<el-table-column label="操作" width="150">
					<template #default="scope">
						<el-button type="danger" size="small" @click="handleDelete(scope.row)">
							<el-icon><Delete /></el-icon>删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 批量添加科目对话框 -->
		<el-dialog v-model="dialogVisible" title="批量添加科目" width="500px">
			<el-form ref="formRef" :model="{ newSubjects }">
				<el-form-item
					prop="newSubjects"
					:rules="rules.newSubjects"
					label="科目列表"
					label-width="80px"
				>
					<el-input
						v-model="newSubjects"
						type="textarea"
						:rows="10"
						placeholder="请输入科目名称，每行一个"
					/>
				</el-form-item>
				<div class="dialog-tip">提示：每行输入一个科目名称</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleBatchAdd">确认添加</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped lang="scss">
.subject-manage {
	padding: 20px;
	height: 100%;
	box-sizing: border-box;
	background-color: var(--el-bg-color);

	.subject-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;

		h2 {
			margin: 0;
			font-size: 18px;
			font-weight: 500;
		}

		.operation-buttons {
			display: flex;
			gap: 10px;
		}
	}

	.subject-table-card {
		margin-bottom: 20px;
	}

	.dialog-tip {
		color: #909399;
		font-size: 12px;
		margin-top: -10px;
		margin-left: 80px;
	}
}
</style>
